package com.rlz.base.base

import android.text.TextUtils
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.WebStorage
import android.widget.FrameLayout
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebChromeClient
import com.rlz.base.R
import com.rlz.base.databinding.ActivityWebBinding

/**
 * Created by RLZ
 * on 2021/10/18
 *
 */


abstract class BaseWebActivity : BaseActivity<EmptyModel, EmptyViewModel, ActivityWebBinding>() {

    companion object {
        const val URL_CARRY_STR = "url_carry_str"
    }

    protected var mUrl: String = ""

    protected lateinit var mAgentWeb: AgentWeb

    override fun layoutId(): Int {
        return R.layout.activity_web
    }

    override fun logic() {
        mUrl = intent.getStringExtra(URL_CARRY_STR).toString()
    }

    protected fun loadUrl() {

        if (TextUtils.isEmpty(mUrl)) return

        val layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(mBinding.mContainer, layoutParams)
            .useDefaultIndicator()
            .setWebChromeClient(createClient())
            .createAgentWeb()
            .ready()
            .go(mUrl)
    }

    abstract fun createClient(): WebChromeClient

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        return if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            true
        } else super.onKeyDown(keyCode, event)
    }

    override fun onResume() {
        super.onResume()
        mAgentWeb.webLifeCycle.onResume()
    }

    override fun onPause() {
        super.onPause()
        mAgentWeb.webLifeCycle.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAgentWeb.webLifeCycle.onDestroy()
        WebStorage.getInstance().deleteAllData()
    }

    override fun onBackPressed() {
        if (!mAgentWeb.back()) {
            finish()
        }
    }
}